<?php

namespace App\Http\Controllers\Admin;

use App\AdminUser;
use Illuminate\Http\Request;

class UserController extends Controller
{
    //管理人员列表
    public function index(Request $request)
    {
        $where = array();

        $where[] = ['id', '>', '0'];

        if (isset($request->name)) {

            $name = trim($request->name);

            $tmp = array();

            $tmp[] = 'name';
            $tmp[] = 'like';
            $tmp[] = '%' . $name . '%';
            $where[] = $tmp;

        }

        $users = AdminUser::where($where)->paginate(1)->appends($request->all());
        return view('admin.user.index', compact('users'));
    }

    //管理人员增加
    public function create()
    {
        return view('admin.user.create');
    }

    //管理人员增加行为
    public function store()
    {
        $this->validate(request(), [
            'name' => 'unique:admin_users,name|min:2',
            'password' => 'required|min:5|max:10|alpha_dash',
        ]);

        $name = request('name');
        $password = bcrypt(request('password'));

        AdminUser::create(compact('name', 'password'));

        return redirect('/admin/users');
    }

    //管理人员角色展示
    public function role(AdminUser $user)
    {
        $roles = \App\AdminRole::all();
        $myRoles = $user->roles;
        return view('/admin/user/role', compact('roles', 'myRoles', 'user'));
    }

    //管理人员角色关联
    public function storeRole(\App\AdminUser $user)
    {
        $this->validate(request(),[
            'roles' => 'required|array'
        ]);

        $roles = \App\AdminRole::findMany(request('roles'));
        $myRoles = $user->roles;

        // 对已经有的权限
        $addRoles = $roles->diff($myRoles);
        foreach ($addRoles as $role) {
            $user->roles()->save($role);
        }

        $deleteRoles = $myRoles->diff($roles);
        foreach ($deleteRoles as $role) {
            $user->deleteRole($role);
        }
        return back();
    }
}
